<?php if(!defined('FRAME')) exit('No direct script access allowed');
/**
 * 控制器
 * @author wisoch@hotmail.com
 *
 */
class Controller {
	protected $retrunType = 'html';
	protected $view;

	public function __construct() {
		$this->retrunType = Uri::Instance()->getExt();
		switch ($this->retrunType) {
			case 'html':
			case 'htm' :
				$this->html();
				break;
			case 'json' :
				$this->json();
		}
	}
	public function html() {}
	public function json() {$this->displayJSON(array('status' => 404, 'message' => 'json action not found'));}
	public function display($data = array(), $tpl, $cache = 0, $cacheId = null) {
		isset($this->view)? '': $this->view = View::Instance();
		
		if($cache) {
			$this->view->smarty->caching = true;
			$this->view->smarty->cache_lifetime = $cache;
		}

		foreach($data as $key => $value) {
			$this->view->smarty->assign($key , $value);
		}
		$this->view->smarty->assign('_conf', Config::Instance()->get());
		$this->view->smarty->display($tpl, $cacheId);
		exit();
	}
	public function displayJSON($data = array()) {
		header('Content-type: text/html; charset=UTF-8');
		echo json_encode($data);exit();
	}
	public function fetch($data, $tpl) {
		$this->view = View::Instance();
		foreach($data as $key => $value) {
			$this->view->smarty->assign($key , $value);
		}
		$this->view->smarty->assign('_conf', Config::Instance()->get());
		return $this->view->smarty->fetch($tpl);
	}
	public function backurl() {
		return $this->get('backurl', 'str')? $this->get('backurl', 'str'): '';
		//return isset($_SERVER['HTTP_REFERER'])? $_SERVER['HTTP_REFERER']: ($this->get('backurl', 'str')? $this->get('backurl', 'str'): '');
	}
	public function get($var, $type = 'str', $default = null) {
		if(isset($_GET[$var])) return $this->formate($type, $_GET[$var]);
		return $this->formate($type, $default);
	}
	public function post($var, $type = 'str', $default = null) {
		if(isset($_POST[$var])) return $this->formate($type, $_POST[$var]);
		return $this->formate($type, $default);
	}
	public function cookie($var, $type = 'str', $default = null) {
		if(isset($_COOKIE[$var])) return $this->formate($type, $_COOKIE[$var]);
		return $this->formate($type, $default);
	}
	public function formate($type, $value) {
		switch (strtolower($type)) {
			case 'int' :
				$value = (int)$value;
				break;
			case 'str' :
				$value = (string)htmlspecialchars(trim($value));
				break;
			case 'arr' :
				if(!is_array($value)) {
					$value = (array) $value;
				}
				break;
			case 'float' :
				$value = (float)$value;
				break;
			default:
				$value = NULL;
				break;
		}
		return $value;
	}
	public function isPost() {
		return isset($_SERVER['REQUEST_METHOD']) && strtoupper($_SERVER['REQUEST_METHOD']) == 'POST';
	}
}